package com.research.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.research.file.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping
    @RequestMapping("/report")
    public JSONObject report(){
        long start=System.currentTimeMillis();

        JSONObject json = orderReport();
        log.info("当前线程{} 耗时:{}",Thread.currentThread().getName(), (System.currentTimeMillis() - start));

        return json;

    }

    private JSONObject orderReport() {
        CompletableFuture<String> todayOrderCountFuture = orderService.todayOrderCount();
        CompletableFuture<String> todayTurnoverFuture = orderService.todayTurnover();
        CompletableFuture<String> totalTurnoverFuture = orderService.totalTurnover();

        JSONObject json = new JSONObject();

        todayOrderCountFuture.whenComplete((v, t) -> {
            json.put("todayOrderCountFuture", v);
        });
        todayTurnoverFuture.whenComplete((v, t) -> {
            json.put("todayTurnoverFuture", v);
        });
        totalTurnoverFuture.whenComplete((v, t) -> {
            json.put("totalTurnoverFuture", v);
        });

        CompletableFuture.allOf(todayOrderCountFuture, todayTurnoverFuture, totalTurnoverFuture)
                .thenRun(() -> System.out.println(Thread.currentThread().getName()+":完成！！！！"))
                .join();
        return json;
    }

}
